<template>
  <div class="organization-manage">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" inline>
        <el-form-item label="机构名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入机构名称"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="机构编码">
          <el-input
            v-model="searchForm.code"
            placeholder="请输入机构编码"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            class="search-select"
          >
            <el-option label="正常" value="normal" />
            <el-option label="停用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><RefreshLeft /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="left">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增机构
        </el-button>
        <el-button type="success" @click="handleExpand(true)">
          <el-icon><FolderOpened /></el-icon>展开
        </el-button>
        <el-button type="info" @click="handleExpand(false)">
          <el-icon><Folder /></el-icon>折叠
        </el-button>
      </div>
    </div>

    <!-- 机构树表格 -->
    <el-card shadow="hover">
      <el-table
        :data="orgList"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children' }"
        v-loading="loading"
      >
        <el-table-column prop="name" label="机构名称" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="org-name">
              <el-icon :class="row.type === 'company' ? 'company' : 'dept'">
                <OfficeBuilding v-if="row.type === 'company'" />
                <Briefcase v-else />
              </el-icon>
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="机构编码" width="120" />
        <el-table-column prop="order" label="排序" width="80" />
        <el-table-column prop="leader" label="负责人" width="120" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'normal' ? 'success' : 'danger'">
              {{ row.status === 'normal' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-tooltip content="新增子机构" placement="top">
                <el-button type="primary" link @click="handleAddChild(row)">
                  <el-icon><Plus /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="编辑" placement="top">
                <el-button type="primary" link @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button type="danger" link @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增机构' : '编辑机构'"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="上级机构">
          <el-tree-select
            v-model="formData.parentId"
            :data="orgList"
            :props="{ label: 'name', value: 'id' }"
            placeholder="请选择上级机构"
            clearable
            class="form-select"
          />
        </el-form-item>
        <el-form-item label="机构类型" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio label="company">公司</el-radio>
            <el-radio label="dept">部门</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="机构名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入机构名称" />
        </el-form-item>
        <el-form-item label="机构编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入机构编码" />
        </el-form-item>
        <el-form-item label="排序" prop="order">
          <el-input-number v-model="formData.order" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="负责人" prop="leader">
          <el-input v-model="formData.leader" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="normal">正常</el-radio>
            <el-radio label="disabled">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  RefreshLeft,
  Plus,
  Edit,
  Delete,
  FolderOpened,
  Folder,
  OfficeBuilding,
  Briefcase
} from '@element-plus/icons-vue'

// 机构项接口
interface OrgItem {
  id: string | number
  name: string
  code: string
  type: 'company' | 'dept'
  order: number
  leader: string
  phone: string
  status: 'normal' | 'disabled'
  children?: OrgItem[]
}

// 搜索表单
const searchForm = ref({
  name: '',
  code: '',
  status: ''
})

// 状态定义
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref()
const orgList = ref<OrgItem[]>([])

// 表单数据
const formData = ref({
  id: '',
  name: '',
  code: '',
  type: 'company',
  order: 0,
  leader: '',
  phone: '',
  status: 'normal',
  parentId: null
})

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: '请输入机构名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入机构编码', trigger: 'blur' },
    { pattern: /^[A-Z0-9]+$/, message: '只能包含大写字母和数字', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择机构类型', trigger: 'change' }
  ],
  order: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ],
  leader: [
    { required: true, message: '请输入负责人', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 搜索方法
const handleSearch = () => {
  fetchOrgList()
}

// 重置方法
const handleReset = () => {
  searchForm.value = {
    name: '',
    code: '',
    status: ''
  }
  handleSearch()
}

// 新增方法
const handleAdd = () => {
  dialogType.value = 'add'
  formData.value = {
    id: '',
    name: '',
    code: '',
    type: 'company',
    order: 0,
    leader: '',
    phone: '',
    status: 'normal',
    parentId: null
  }
  dialogVisible.value = true
}

// 新增子机构
const handleAddChild = (row: OrgItem) => {
  dialogType.value = 'add'
  formData.value = {
    id: '',
    name: '',
    code: '',
    type: 'dept',
    order: 0,
    leader: '',
    phone: '',
    status: 'normal',
    parentId: row.id
  }
  dialogVisible.value = true
}

// 编辑方法
const handleEdit = (row: OrgItem) => {
  dialogType.value = 'edit'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 删除方法
const handleDelete = (row: OrgItem) => {
  ElMessageBox.confirm(
    '确定要删除该机构吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 这里调用删除接口
    ElMessage.success('删除成功')
    fetchOrgList()
  })
}

// 展开/折叠
const handleExpand = (expand: boolean) => {
  // 获取表格实例并调用展开/折叠方法
  const tableEl = document.querySelector('.el-table')
  if (tableEl) {
    const rows = tableEl.querySelectorAll('.el-table__row')
    rows.forEach((row: any) => {
      const expandIcon = row.querySelector('.el-table__expand-icon')
      if (expandIcon) {
        const isExpanded = expandIcon.classList.contains('el-table__expand-icon--expanded')
        if (expand && !isExpanded || !expand && isExpanded) {
          expandIcon.click()
        }
      }
    })
  }
}

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid: boolean) => {
    if (valid) {
      // 这里调用新增或编辑接口
      ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
      dialogVisible.value = false
      fetchOrgList()
    }
  })
}

// 获取机构列表
const fetchOrgList = () => {
  loading.value = true
  // 这里调用获取机构列表接口
  setTimeout(() => {
    // 模拟数据
    orgList.value = [
      {
        id: 1,
        name: '总公司',
        code: 'HQ',
        type: 'company',
        order: 1,
        leader: '张三',
        phone: '13800138000',
        status: 'normal',
        children: [
          {
            id: 2,
            name: '研发部',
            code: 'RD',
            type: 'dept',
            order: 1,
            leader: '李四',
            phone: '13800138001',
            status: 'normal'
          },
          {
            id: 3,
            name: '市场部',
            code: 'MK',
            type: 'dept',
            order: 2,
            leader: '王五',
            phone: '13800138002',
            status: 'normal'
          }
        ]
      }
    ]
    loading.value = false
  }, 500)
}

// 初始化
onMounted(() => {
  fetchOrgList()
})
</script>

<style lang="scss" scoped>
.organization-manage {
  .search-card {
    margin-bottom: 16px;
    
    :deep(.el-card__body) {
      padding: 16px;
    }
    
    .search-input {
      width: 200px;
    }
    
    .search-select {
      width: 160px;
    }
  }
  
  .toolbar {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    gap: 16px;
    
    .el-button {
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
      
      .el-icon {
        margin-right: 4px;
      }
    }
  }
  
  .el-card {
    border-radius: 8px;
    transition: all 0.3s ease;
    
    &:hover {
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    }
  }
  
  .org-name {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .el-icon {
      padding: 4px;
      border-radius: 4px;
      transition: all 0.3s ease;
      
      &.company {
        background: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
      }
      
      &.dept {
        background: var(--el-color-success-light-9);
        color: var(--el-color-success);
      }
    }
  }
  
  :deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
    
    .el-button-group {
      .el-button {
        padding: 4px 8px;
        
        .el-icon {
          font-size: 16px;
        }
        
        &:hover {
          .el-icon {
            transform: scale(1.2);
          }
        }
      }
    }
  }
  
  .form-select {
    width: 100%;
  }
}
</style> 